package com.xsj.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys;
import java.util.Date;
import javax.crypto.SecretKey;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class JwtUtils {
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    public JwtUtils() {
    }

    public String generateToken(String username, long userId) {
        Claims claims = Jwts.claims().setSubject(username);
        claims.put("issuedAt", new Date());
        claims.put("userId", userId);
        new Date(System.currentTimeMillis() + this.expiration);
        SecretKey key = Keys.hmacShaKeyFor(this.secret.getBytes());
        return Jwts.builder().setClaims(claims).signWith(key, SignatureAlgorithm.HS256).compact();
    }

    public String getUsernameFromToken(String token) {
        try {
            SecretKey key = Keys.hmacShaKeyFor(this.secret.getBytes());
            Claims body = (Claims)Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
            return body.getSubject();
        } catch (Exception var4) {
            return null;
        }
    }

    public Long getUserIdFromToken(String token) {
        try {
            SecretKey key = Keys.hmacShaKeyFor(this.secret.getBytes());
            Claims body = (Claims)Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
            return (Long)body.get("userId");
        } catch (Exception var4) {
            var4.printStackTrace();
            return null;
        }
    }

    public boolean validateToken(String token) {
        try {
            SecretKey key = Keys.hmacShaKeyFor(this.secret.getBytes());
            Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
            return true;
        } catch (MalformedJwtException | SecurityException var3) {
            System.err.println("Invalid JWT signature: " + var3.getMessage());
        } catch (ExpiredJwtException var4) {
            System.err.println("Expired JWT token: " + var4.getMessage());
        } catch (UnsupportedJwtException var5) {
            System.err.println("Unsupported JWT token: " + var5.getMessage());
        } catch (IllegalArgumentException var6) {
            System.err.println("JWT claims string is empty: " + var6.getMessage());
        }

        return false;
    }

    public Long getExpiration() {
        return this.expiration;
    }
}
